package net.wangds.yunz.auth.handler;

import net.wangds.auth.token.cache.TokenCache;
import net.wangds.log.helper.LogHelper;
//import net.wangds.program.auth.AuthConstants;
import net.wangds.spring.utils.SpringUtils;
import net.wangds.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

@Component
public class LogoutSuccessHandler implements org.springframework.security.web.authentication.logout.LogoutSuccessHandler {

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        LogHelper.dev("on logout success:"+ JsonUtils.toJsonStr(authentication));
        String auth = request.getHeader(HttpHeaders.AUTHORIZATION);

        LogHelper.dev(()->"logout auth:"+auth);


        TokenCache cache = SpringUtils.getBean(TokenCache.class);
        String token=StringUtils.replace(auth, "Bearer ", "");
        Serializable authInfo = cache.getToken(token);
        // 清除redis
        if(authInfo!=null){
            LogHelper.dev(()->"logout user info:"+JsonUtils.toJsonStr(authInfo));
            cache.evictToken(token);
            LogHelper.dev(()->"登出过程：清理缓存");
        }

        //String accessToken = request.getHeader(JwtTokenUtil.tokenHeader);
        //if (!StringUtils.isEmpty(accessToken)) {
            //Claims claims = JwtTokenUtil.getClaims(accessToken);
            //RedisUtil.delete(claims.getSubject());
            //logger.info("用户 [ {} ] 安全登出", claims.getSubject());
            //GlobalResultUtil.out(response, GlobalResultUtil.success(ResultEnum.LOGOUT_SUCCESS));
        //}
        //清空上下文
        SecurityContextHolder.clearContext();
        LogHelper.dev(()->"登出过程：清理上下文");


        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,HEAD,OPTIONS,PUT,DELETE,TRACE,CONNECT");
        response.setHeader("Access-Control-Max-Age", "36000");
        response.setHeader("Access-Control-Allow-Headers","*");
    }
}
